#https://pypi.org/project/websocket_client/
import websocket
import time
import sys

mytime=0

def on_message(ws, message):
    #print(message)
    global mytime
    # every second store quotes
    if time.time()>mytime:
        mytime=time.time()
        f = open("quotes.txt", "w")
        f.write(message)
        f.close()
        #ws.keep_running = False
        my_file = open("stream_enabled.txt", "r")
        content = my_file.readline(1)
        my_file.close()
        if content == "0":
            ws.keep_running = False
	

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    #ws.send('{"type":"subscribe","symbol":"AAPL"}')
    #ws.send('{"type":"subscribe","symbol":"AMZN"}')
    #ws.send('{"type":"subscribe","symbol":"BINANCE:BTCUSDT"}')
    #ws.send('{"type":"subscribe","symbol":"BINANCE:ETHUSDT"}')
    #ws.send('{"type":"subscribe","symbol":"BINANCE:XRPUSDT"}')
    #ws.send('{"type":"subscribe","symbol":"BINANCE:BNBUSDT"}')
    #ws.send('{"type":"subscribe","symbol":"IC MARKETS:1"}')
    my_file = open("tickers.txt", "r")
    content = my_file.read()
    content_list = content.split(",")
    my_file.close()
    #print(content_list[0])
    for contentitem in content_list:
         #print(contentitem)
         ws.send('{"type":"subscribe","symbol":"'+contentitem+'"}')
    #ws.keep_running = False

if __name__ == "__main__":
    websocket.enableTrace(True)
    # sys.argv[1] argument 1 is the token api key
    ws = websocket.WebSocketApp("wss://ws.finnhub.io?token="+sys.argv[1],
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()